//
//  startView.m
//  SmartHome
//
//  Created by 赵嘉诚 on 15/3/12.
//  Copyright (c) 2015年 赵嘉诚. All rights reserved.
//

#import "startView.h"
#import "registView.h"

@interface startView () <createNewUser, UITableViewDelegate, UITableViewDataSource>
{
    UIImage *unSelected, *selected;
    BOOL updata, remember,isShowTableView;
    NSString *listPath;
    NSArray *userList;
    NSManagedObjectContext *context;
    CGFloat increaseHeight;
}

@property (nonatomic, strong) UITextField *userName;
@property (nonatomic, strong) UITextField *userPassword;
@property (nonatomic, strong) UIButton *loadButton;
@property (nonatomic, strong) UIButton *noNumber;
@property (nonatomic, strong) UIButton *updataButton;
@property (nonatomic, strong) UIButton *rememberButton;

@property (nonatomic, strong) UITableView *userTableView;

@end

@implementation startView

- (UIButton *)noNumber
{
    if(!_noNumber){
        _noNumber = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 95, self.view.bounds.size.height - 35, 90, 30)];
        
        [_noNumber setTitle:@"没有账号？" forState:UIControlStateNormal];
        [_noNumber setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _noNumber.titleLabel.font = [UIFont systemFontOfSize:15];
        _noNumber.titleLabel.textAlignment = NSTextAlignmentRight;
        [_noNumber addTarget:self action:@selector(pressNoNumberButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _noNumber;
}

- (UITextField *)userName
{
    if(!_userName){
        _userName = [[UITextField alloc] initWithFrame:CGRectMake(30, self.view.bounds.size.height * 0.2 + 105, self.view.bounds.size.width - 60, 35)];
        
        UIImage *background = GET_IAMGE_WITH_NAME(@"Image/startView/input_bg");
        _userName.background = background;
        
        UIImage *leftImage = GET_IAMGE_WITH_NAME(@"Image/startView/icon_user");
        UIImageView *imageView = [[UIImageView alloc] initWithImage:leftImage];
        [imageView setFrame:CGRectMake(0, 0, 38, 38)];
        _userName.leftView = imageView;
        _userName.leftViewMode = UITextFieldViewModeAlways;
        
        UIImage *rightImage = GET_IAMGE_WITH_NAME(@"Image/startView/arrowdown");
        UIImageView *rightImageView = [[UIImageView alloc] initWithImage:rightImage];
        [rightImageView setFrame:CGRectMake(0, 0, 25, 25)];
        _userName.rightView = rightImageView;
        _userName.rightViewMode = UITextFieldViewModeAlways;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showUserTableView)];
        [_userName addGestureRecognizer:tap];
        _userName.rightView.userInteractionEnabled = YES;
        
        
        _userName.textColor = [UIColor lightGrayColor];
        _userName.font = [UIFont systemFontOfSize:20];
        _userName.keyboardType = UIKeyboardTypeAlphabet;
        _userName.returnKeyType = UIReturnKeyDone;  //返回键类型是Done
        _userName.autocapitalizationType = UITextAutocapitalizationTypeNone;  //手写字母大写 关闭
        _userName.autocorrectionType = UITextAutocorrectionTypeNo;  //自动改正 关闭
        _userName.clearButtonMode = UITextFieldViewModeWhileEditing;   //最后面添加一个 ×
        _userName.backgroundColor = [UIColor clearColor];
        _userName.secureTextEntry = NO;   //非密文
        
        UIGraphicsEndImageContext();
    }
    return _userName;
}

- (UITextField *)userPassword
{
    if(!_userPassword){
        _userPassword = [[UITextField alloc] initWithFrame:CGRectMake(30, self.view.bounds.size.height * 0.2 + 162, self.view.bounds.size.width - 60, 35)];
        
        UIImage *background = GET_IAMGE_WITH_NAME(@"Image/startView/input_bg");
        _userPassword.background = background;
        
        UIImage *leftImage = GET_IAMGE_WITH_NAME(@"Image/startView/icon_password");
        UIImageView *imageView = [[UIImageView alloc] initWithImage:leftImage];
        [imageView setFrame:CGRectMake(0, 0, 40, 40)];
        _userPassword.leftView = imageView;
        _userPassword.leftViewMode = UITextFieldViewModeAlways;
        
        _userPassword.textColor = [UIColor lightGrayColor];
        _userPassword.font = [UIFont systemFontOfSize:20];
        _userPassword.keyboardType = UIKeyboardTypeAlphabet;
        _userPassword.returnKeyType = UIReturnKeyDone;  //返回键类型是Done
        _userPassword.autocapitalizationType = UITextAutocapitalizationTypeNone;  //手写字母大写 关闭
        _userPassword.autocorrectionType = UITextAutocorrectionTypeNo;  //自动改正 关闭
        _userPassword.clearButtonMode = UITextFieldViewModeWhileEditing;   //最后面添加一个 ×
        _userPassword.backgroundColor = [UIColor clearColor];
        _userPassword.secureTextEntry = YES;   //密文
    }
    return _userPassword;
}

- (UIButton *)updataButton
{
    if(!_updataButton){
        _updataButton = [[UIButton alloc] initWithFrame:CGRectMake(30, self.view.bounds.size.height * 0.2 + 207, 25, 25)];
        if(updata){
            [_updataButton setBackgroundImage:selected forState:UIControlStateNormal];
        }
        _updataButton.layer.cornerRadius = 5;
        _updataButton.layer.borderColor = [UIColor blackColor].CGColor;
        _updataButton.layer.borderWidth = 1;
        _updataButton.layer.masksToBounds = YES;
        [_updataButton addTarget:self action:@selector(pressUpdataButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _updataButton;
}

- (void)addUpdataLabel
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(65, self.view.bounds.size.height * 0.2 + 207, 80, 25)];
    [button setTitle:@"数据同步" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:16];
    [button addTarget:self action:@selector(pressUpdataButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    button = nil;
}

- (UIButton *)rememberButton
{
    if(!_rememberButton){
        _rememberButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 145, self.view.bounds.size.height * 0.2 + 207, 25, 25)];
        if(remember){
            [_rememberButton setBackgroundImage:selected forState:UIControlStateNormal];
        }
        _rememberButton.layer.cornerRadius = 5;
        _rememberButton.layer.borderColor = [UIColor blackColor].CGColor;
        _rememberButton.layer.borderWidth = 1;
        _rememberButton.layer.masksToBounds = YES;
        [_rememberButton addTarget:self action:@selector(pressRememberButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rememberButton;
}

- (void)addRememberLabel
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 110, self.view.bounds.size.height * 0.2 + 207, 80, 25)];
    [button setTitle:@"记住密码" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:16];
    [button addTarget:self action:@selector(pressRememberButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    button = nil;
}

- (UIButton *)loadButton
{
    if(!_loadButton){
        _loadButton = [[UIButton alloc] initWithFrame:CGRectMake(30, self.view.bounds.size.height * 0.2 + 245, self.view.bounds.size.width - 60, 35)];
        
        UIImage *background = GET_IAMGE_WITH_NAME(@"Image/startView/main_button_n");
        [_loadButton setBackgroundImage:background forState:UIControlStateNormal];
        [_loadButton setTitle:@"登录" forState:UIControlStateNormal];
        [_loadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        _loadButton.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:22];
        [_loadButton addTarget:self action:@selector(pressLoadButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loadButton;
}

- (void)addBackGroundImage
{
    UIImage *background = GET_IAMGE_WITH_NAME(@"Image/startView/login_bg");
    UIImageView *imageView = [[UIImageView alloc] initWithImage:background];
    [imageView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    [self.view addSubview:imageView];
    imageView = nil;
}

//头像
- (void)addHeadPortrait
{
    UIImage *head = GET_IAMGE_WITH_NAME(@"Image/startView/icon_logo");
    UIImageView *imageView = [[UIImageView alloc] initWithImage:head];
    [imageView setFrame:CGRectMake((self.view.bounds.size.width - self.view.bounds.size.height * 0.2) / 2, 45,
                                   self.view.bounds.size.height * 0.2, self.view.bounds.size.height * 0.2)];
    [self.view addSubview:imageView];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height + 50, self.view.bounds.size.width, 30)];
    label.text = @"Smart Home";
    label.font = [UIFont systemFontOfSize:25];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
}

- (UITableView *)userTableView
{
    if(!_userTableView){
        _userTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 2 - 20,
                                                                       self.view.bounds.size.height * 0.2 + 140,
                                                                       self.view.bounds.size.width / 2 - 10, 100) style:UITableViewStylePlain];
        _userTableView.tableFooterView = [[UIView alloc] init];
        _userTableView.backgroundColor = [UIColor blackColor];
        _userTableView.alpha = 0.8;
        _userTableView.delegate = self;
        _userTableView.dataSource = self;
        _userTableView.layer.cornerRadius = 5.0;
        _userTableView.layer.masksToBounds = YES;
    }
    return _userTableView;
}

- (void)showUserTableView
{
    if(isShowTableView == YES){
        [self removeTableView];
    }else{
        [self.view addSubview:self.userTableView];
        isShowTableView = YES;
    }
}

#pragma mark - UITableViewDataSource 协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CGFloat height = 0.0;
    if(userList.count == 0){
        height = 10.0;
    }else if(userList.count == 1){
        height = 30.0;
    }else if(userList.count == 2){
        height = 61.0;
    }else if(userList.count == 3){
        height = 92.0;
    }else{
        height = 100.0;
    }
    [tableView setFrame:CGRectMake(self.view.bounds.size.width / 2 - 20,
                                   self.view.bounds.size.height * 0.2 + 140,
                                   self.view.bounds.size.width / 2 - 10, height)];
    return userList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *CellIndentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    [cell.textLabel setFont:[UIFont systemFontOfSize:20]];
    [cell.textLabel setTextColor:[UIColor whiteColor]];
    cell.textLabel.text = [[userList objectAtIndex:(userList.count - indexPath.row - 1)] objectForKey:@"name"];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.userName.text = [[userList objectAtIndex:(userList.count - indexPath.row - 1)] objectForKey:@"name"];
    self.userPassword.text = [[userList objectAtIndex:(userList.count - indexPath.row - 1)] objectForKey:@"key"];
    
    [tableView removeFromSuperview];
}

#pragma mark - 按钮响应函数
- (void)pressRememberButton
{
    if(remember){
        [self.rememberButton setBackgroundImage:unSelected forState:UIControlStateNormal];
    }else{
        [self.rememberButton setBackgroundImage:selected forState:UIControlStateNormal];
    }
    remember = !remember;
}

- (void)pressUpdataButton
{
    if(updata){
        [self.updataButton setBackgroundImage:unSelected forState:UIControlStateNormal];
    }else{
        [self.updataButton setBackgroundImage:selected forState:UIControlStateNormal];
    }
    updata = !updata;
}

- (void)pressNoNumberButton
{
    registView *myRegisterView = [[registView alloc] initWithNibName:nil bundle:nil];
    myRegisterView.delegate = self;
    myRegisterView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:myRegisterView animated:YES completion:^{}];
}

- (void)removeTableView
{
    if(isShowTableView == YES){
        isShowTableView = NO;
        [self.userTableView removeFromSuperview];
    }
}

//储存用户信息（记住密码）
- (void)saveUserInfo
{
    NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:userList];
    if(userList){
        NSDictionary *user;
        for (user in userList) {
            if([[user objectForKey:@"name"] isEqualToString:self.userName.text]){
                [newArray removeObject:user];
                break;
            }
        }
    }
    NSDictionary *newUser;
    if(remember){
        newUser = [[NSDictionary alloc]
                   initWithObjectsAndKeys:self.userName.text,@"name", self.userPassword.text, @"key", nil];
    }else{
        newUser = [[NSDictionary alloc]
                   initWithObjectsAndKeys:self.userName.text,@"name", @"", @"key", nil];
    }
    [newArray addObject:newUser];
    [newArray writeToFile:listPath atomically:YES];
}

#pragma mark -- createNewUser 协议
- (int)newUserOfName:(NSString *)name andKey:(NSString *)key serverIP:(NSString *)serverIP port:(NSInteger)port serverId:(NSString *)serverId
{
    NSArray *arr = [self getStatusesByUserName:name];
    if([arr count] != 0){
        return 1;
    }else{
        [self addUserWithName:name key:key serverIP:serverIP port:port serverId:serverId];
        return 0;
    }
}

- (void)modalViewControllerDidClickedDismissButton:(registView *)viewController
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

//点击登陆按钮
- (void)pressLoadButton
{
    if([self.userName.text isEqualToString:@""] || [self.userPassword.text isEqualToString:@""]){
        //警告视图
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                            message:@"用户名或密码不能为空"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"OK", nil];
        [alertView show];
    }else{
        NSArray *arr = [self getStatusesByUserName:self.userName.text];
        if([arr count] != 0){
            Entity *myEntity = [arr objectAtIndex:0];
            NSString *key = myEntity.key;
            if([self.userPassword.text isEqualToString:key]){     //登录成功
                [self saveUserInfo];
                [self.delegate loadServerWithEnitity:myEntity andIsUpdata:updata];
                return ;
            }
        }
    }
    //警告视图
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                        message:@"用户名或密码错误"
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"OK", nil];
    [alertView show];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    unSelected = GET_IAMGE_WITH_NAME(@"Image/startView/info_unselected");
    selected = GET_IAMGE_WITH_NAME(@"Image/startView/info_selected");
    updata = NO;
    remember = NO;
    isShowTableView = NO;
    
    [self addBackGroundImage];
    [self addHeadPortrait];
    [self.view addSubview:self.noNumber];
    [self.view addSubview:self.userName];
    [self.view addSubview:self.userPassword];
    [self.view addSubview:self.loadButton];
    [self.view addSubview:self.updataButton];
    [self addUpdataLabel];
    [self.view addSubview:self.rememberButton];
    [self addRememberLabel];
    
    listPath = [NSHomeDirectory() stringByAppendingPathComponent:LIST_NAME];
    userList = [[NSArray alloc] initWithContentsOfFile:listPath];
    
    if(userList){
        NSUInteger count = [userList count];
        NSDictionary *user = [userList objectAtIndex:count - 1];
        self.userName.text = [user objectForKey:@"name"];
        self.userPassword.text = [user objectForKey:@"key"];
        if(![self.userPassword.text isEqualToString:@""]){
            [self.rememberButton setBackgroundImage:selected forState:UIControlStateNormal];
            remember = YES;
        }
    }
    
    /***********************************数据库*******************************************/
    NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
    
    NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@",dir);
    NSString *path=[dir stringByAppendingPathComponent:DB_NAME];
    NSURL *url=[NSURL fileURLWithPath:path];
    //添加SQLite持久存储到解析器
    NSError *error;
    [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    if(error){
        NSLog(@"数据库打开失败！错误:%@",error.localizedDescription);
    }else{
        context=[[NSManagedObjectContext alloc]init];
        context.persistentStoreCoordinator=storeCoordinator;
        NSLog(@"数据库打开成功！");
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //注册键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //解除键盘出现的通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    //解除键盘隐藏的通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notif
{
    [self removeTableView];
    //获得键盘尺寸
    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    increaseHeight = self.view.bounds.size.height * 0.44 + 245 - (self.view.bounds.size.height - keyboardSize.height);
    if(increaseHeight > 0){
        self.view.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -increaseHeight);
    }
}

- (void)keyboardWillHide:(NSNotification *)notif
{
    self.view.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 0);
}

#pragma mark -- Core Data 函数
//新增
-(void)addUserWithName:(NSString *)name key:(NSString *)key serverIP:(NSString *)serverIP port:(NSInteger)port serverId:(NSString *)severId{
    //添加一个对象
    Entity *us = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:context];
    us.name = name;
    us.key = key;
    us.ip = serverIP;
    NSNumber *myPort = [NSNumber numberWithInteger:port];
    us.port = myPort;
    us.serverId = severId;
    NSLog(@"新建用户:%@",name);
    NSError *error;
    //保存上下文
    if (![context save:&error]) {
        NSLog(@"添加过程中发生错误,错误信息：%@！",error.localizedDescription);
    }
}

//查询
-(NSArray *)getStatusesByUserName:(NSString *)name{
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Entity"];
    request.predicate=[NSPredicate predicateWithFormat:@"name=%@",name];
    NSArray *array=[context executeFetchRequest:request error:nil];
    return  array;
}

//修改
-(void)modifyUserWithName:(NSString *)name key:(NSString *)key{
    Entity *us=[[self getStatusesByUserName:name] objectAtIndex:0];
    us.key = key;
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"修改过程中发生错误,错误信息：%@",error.localizedDescription);
    }
}

//删除
-(void)removeUser:(Entity *)user{
    [context deleteObject:user];
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"删除过程中发生错误，错误信息：%@!",error.localizedDescription);
    }
}

//键盘出现时,点击，键盘收起
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.userTableView removeFromSuperview];
    [self.view endEditing:YES];
}

@end
